﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "SnakeGame.h"

void InitSystem()	//初始化控制台
{
    //设置控制台窗⼝的⻓宽：设置控制台窗⼝的⼤⼩，30⾏，100列
    system("mode con cols=100 lines=30");
    //设置cmd窗⼝名称
    system("title 贪吃蛇");
    
    //获取标准输出的句柄（用来表示不同设备的数值）
    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);

    //影藏光标操作
    CONSOLE_CURSOR_INFO CursorInfo;
    GetConsoleCursorInfo(hOutput, &CursorInfo);//获取控制台光标信息
    CursorInfo.bVisible = false; //隐藏控制台光标
    SetConsoleCursorInfo(hOutput, &CursorInfo);//设置控制台光标状态
}

void Setpos(short x, short y)//设置光标坐标
{
    COORD pos = { x , y };
    //获取标准输出的句柄（用来表示不同设备的数值）
    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    //设置标准输出上光标的位置为pos
    SetConsoleCursorPosition(hOutput, pos);
}

void WelcomeToGame()//打印欢迎界面
{
    Setpos(40,14);
    printf("欢迎来到贪吃蛇小游戏");
    Setpos(40, 25);
    system("pause");
    system("cls");
    Setpos(25, 12);
    printf("用 ↑ . ↓ . ← . → 分别控制蛇的移动， F3为加速，F4为减速\n");
    Setpos(25, 13);
    printf("加速将能得到更高的分数。\n");
    Setpos(40, 25);
    system("pause");
    system("cls"); 
}

void CreateMap()//打印地图
{
    int i = 0;
    //上（0，0）-（56，0）
    Setpos(0, 0);
    for (int i = 0; i < COL; i += 2)
    {
        wprintf(L"%c", WALL);
    }
    //下（0，26）-（56，26）
    Setpos(0, ROW-1);
    for (int i = 0; i < COL; i += 2)
    {
        wprintf(L"%c", WALL);
    }
    //左（0，1）-（0，25）
    for (int i = 1; i < ROW-1; i++)
    {
        Setpos(0, i);
        wprintf(L"%c", WALL);
    }
     //右（56，1）-（56，25）
    for (int i = 1; i < ROW-1; i++)
    {
        Setpos(COL-2, i);
        wprintf(L"%c", WALL);
    }
}

void PrintSnake(pSnake ps)//打印蛇的身体
{
    pSnakeNode cur = ps->_pSnake;
    while (cur)
    {
        Setpos(cur->x, cur->y);
        wprintf(L"%c", BODY);
        cur = cur->next;
    }
}

void InitSnakeData(pSnake ps)//初始化贪吃蛇数据
{
    ps->_SleepTime = INIT_SLEEPTIME;
    ps->_Score = INIT_SCORE;
    ps->_Status = INIT_STATUS;
    ps->_Dir = INIT_Dir;
    ps->_Add = INIT_Add;
}

void InitSnake(pSnake ps)//初始化蛇
{
    pSnakeNode cur = NULL;
    int i = 0;
    //创建舍身节点，并初始化坐标
    //头插法
    for (int i = 0; i < INIT_LEN; i++)
    {
        //创建蛇身的节点
        cur = (pSnakeNode)malloc(sizeof(SnakeNode));
        if (cur == NULL)
        {
            perror("InitSnake()::malloc()");
            exit(1);    //创空间出错直接中断
        }
        //设置坐标
        cur->next = NULL;
        cur->x = INIT_POS_X + i * 2;
        cur->y = INIT_POS_Y;
        
        //头插法
        if (ps->_pSnake == NULL)
        {
            ps->_pSnake = cur;
        }
        else
        {
            cur->next = ps->_pSnake;
            ps->_pSnake = cur;
        }
    }
    //打印蛇的身体
    PrintSnake(ps);
 
    //初始化贪吃蛇数据
    InitSnakeData(ps);
}

void CreateFood(pSnake ps)//创造第一个食物
{
    int x = 0;
    int y = 0;

    while (true)
    {
        // x = rand() % 53 + 2;
        x = rand() % (COL-5) + 2;
        //产生的x坐标应该是2的倍数，这样才可能和蛇头坐标对齐。
        if (x % 2 != 0)  continue;  
        //y = rand() % 25 + 1;
        y = rand() % (ROW-2) + 1;

        pSnakeNode cur = ps->_pSnake;
        while (cur)
        {
            if (cur->x == x && cur->y == y)    continue;
            cur = cur->next;
        }

        pSnakeNode pFood = (pSnakeNode)malloc(sizeof(SnakeNode));
        if (pFood == NULL)
        {
            perror("CreateSnake()::malloc()");
            exit(2);    //创空间出错直接中断
        }
        else
        {
            pFood->x = x;
            pFood->y = y;
            Setpos(pFood->x, pFood->y);
            wprintf(L"%c", FOOD);
            ps->_pFood = pFood;
        }
        break;
    }
}

void GameStart(pSnake ps)			//开始前的初始化
{
	//初始化控制台
	InitSystem();

    //打印欢迎界面
    WelcomeToGame();

    //打印地图
    CreateMap();

    //初始化蛇
    InitSnake(ps);
    //创造第一个食物
    CreateFood(ps);
}

void PrintHelpInfo()//打印帮助信息
{
    Setpos(64, 10);
    printf("游戏规则：");
    Setpos(64, 11);
    printf("不能穿墙，不能咬到自己\n");
    Setpos(64, 12);
    printf("用↑.↓.←.→分别控制蛇的移动.");
    Setpos(64, 13);
    printf("F1 为加速，F2 为减速\n");
    Setpos(64, 14);
    printf("ESC ：退出游戏 , space：暂停游戏.");
}

void Pause()	//暂停游戏
{
    while (1)
    {
        Sleep(300);
        if (KEY_PRESS(VK_SPACE))
        {
            break;
        }
    }
}

void EatFood(pSnakeNode pnode, pSnake ps)//下一个位置是食物
{
    pnode->next = ps->_pSnake;
    ps->_pSnake = pnode;
  
    ps->_Score += ps->_Add; //吃到食物时加分

    PrintSnake(ps);
    free(ps->_pFood);
    CreateFood(ps);
}

void NoFood(pSnakeNode pnode, pSnake ps)//下一个位置不是食物
{
    pSnakeNode cur = ps->_pSnake;
    if (cur == NULL)
    {
        perror("NoFood()::ps->_pSnake==NULL");
        exit(4);
    }
    if (cur->next == NULL)
    {
        cur = NULL;
        free(cur);
        ps->_pSnake = pnode;
    }
    else
    {
        while (cur->next->next)
        {
            cur = cur->next;
        }
        Setpos(cur->next->x, cur->next->y);
        wprintf(L"%c", L' ');
        free(cur->next);
        cur->next = NULL;
        pnode->next = ps->_pSnake;
        ps->_pSnake = pnode;
    }

    PrintSnake(ps);
    CreateMap();
}

void KillByWall(pSnake ps)//撞墙
{
    pSnakeNode cur = ps->_pSnake;
    if ((cur->x <= 0) || (cur->x >= COL-2) || (cur->y <= 0) || (cur->y >= ROW-1))    ps->_Status = KILL_BY_WALL;
}

void KillBySelf(pSnake ps)//撞自身
{
    pSnakeNode cur = ps->_pSnake->next;
    while (cur)
    {
        if (cur->x == ps->_pSnake->x && cur->y == ps->_pSnake->y)
        {
            ps->_Status = KILL_BY_SELF;
            break;
        }
        cur = cur->next;
    }
}

void SnakeMove(pSnake ps)//蛇的移动
{
    pSnakeNode cur = (pSnakeNode)malloc(sizeof(SnakeNode));
    if (cur == NULL)
    {
        perror("SnakeMove(ps)::maloc()");
        exit(3);
    }
    cur->next = NULL;
    switch(ps->_Dir)
    {
    case UP:
        cur->x = ps->_pSnake->x;
        cur->y = ps->_pSnake->y - 1;
        break;
    case DOWN:
        cur->x = ps->_pSnake->x;
        cur->y = ps->_pSnake->y + 1;
        break;
    case LEFT:
        cur->x = ps->_pSnake->x - 2;
        cur->y = ps->_pSnake->y;
        break;
    case RIGHT:
        cur->x = ps->_pSnake->x + 2;
        cur->y = ps->_pSnake->y;
        break;
    }
   
    if (ps->_pFood->x == cur->x && ps->_pFood->y == cur->y) EatFood(cur, ps);  //下一个位置是食物
    else NoFood(cur, ps);

    KillByWall(ps);
    KillBySelf(ps);
}

void GameRun(pSnake ps)//运行游戏
{
    PrintHelpInfo();//打印帮助信息
    
    while (ps->_Status == OK)
    {
        Setpos(64, 16);
        printf("得分：%d ", ps->_Score);
        printf("每个食物得分：%d分", ps->_Add);
        Setpos(64, 17);
        if (KEY_PRESS(VK_UP) && ps->_Dir != DOWN)
        {
            ps->_Dir = UP;
        }
        else if (KEY_PRESS(VK_DOWN) && ps->_Dir != UP)
        {
            ps->_Dir = DOWN;
        }
        else if (KEY_PRESS(VK_LEFT) && ps->_Dir != RIGHT)
        {
            ps->_Dir = LEFT;
        }
        else if (KEY_PRESS(VK_RIGHT) && ps->_Dir != LEFT)
        {
            ps->_Dir = RIGHT;
        }
        else if (KEY_PRESS(VK_SPACE))
        {
            Pause();
        }
        else if (KEY_PRESS(VK_ESCAPE))
        {
            ps->_Status = END_NOMAL;
            break;
        }
        else if (KEY_PRESS(VK_F1))
        {
            if (ps->_SleepTime >= 50)
            {
                ps->_SleepTime -= 30;
                ps->_Add += 2;
            }
        }
        else if (KEY_PRESS(VK_F2))
        {
            if (ps->_SleepTime < 350)
            {
                ps->_SleepTime += 30;
                ps->_Add -= 2;
                if (ps->_SleepTime == 350)
                {
                    ps->_Add = 1;
                }
            }
        }
        //蛇每次一定之间要休眠的时间，时间短，蛇移动速度就快
        Sleep(ps->_SleepTime);
        SnakeMove(ps);//蛇的移动
    }
}

void GameEnd(pSnake ps)//游戏结束
{
    pSnakeNode cur = ps->_pSnake;
    Setpos(24, 12);
    switch (ps->_Status)
    {
    case END_NOMAL:
        printf("您主动退出游戏\n");
        break;
    case KILL_BY_SELF:
        printf("您撞上自己了 ,游戏结束!\n");
        break;
    case KILL_BY_WALL:
        printf("您撞墙了,游戏结束!\n");
        break;
    }

    //释放蛇身的节点
    while (cur)
    {
        pSnakeNode del = cur;
        cur = cur->next;
        free(del);
    }

}